package com.archermind.style.service;

import com.archermind.style.bean.Attachment;
import com.archermind.style.bean.AttachmentFolder;
import com.archermind.style.pojo.Constants;
import com.feng.fengDUtil.BaseService;
import com.archermind.style.util.ImageUtil;
import com.archermind.style.util.Search;
import com.feng.fengDUtil.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class AttachmentService extends BaseService {

    private static final Logger log = LoggerFactory.getLogger(AttachmentService.class);

    public Page query(Page page,Search search) {
        ArrayList params = new ArrayList();
        String sql = "select u.*," +
                "(select s.name From user s where s.id = u.creator limit 1) as creatorName " +
                " from attachment u where 1=1 ";
        if(StringUtils.isNotEmpty(search.getName())){
            sql+=" and u.name like ?";
            params.add(processLike(search.getName()));
        }
        if(search.getFolderId()!=null){
            sql+=" and u.folderId = ?";
            params.add(search.getFolderId());
        }

        sql+="  order by cast(u.name as DECIMAL) asc";
        findPageList(Map.class,sql,page,params.toArray());
        return page;
    }




    public List<Attachment> selectExistsFiles(Integer folderId, List<String> names) {
        ArrayList params = new ArrayList();
        params.add(folderId);
        params.addAll(names);
        List<Attachment> items = sql("select * from attachment where folderId = ? and name in ("+genePlaceHolders(names.size())+")").list(Attachment.class,params.toArray());
        return items;
    }

    public List<AttachmentFolder> listFolders(String folder) {
        ArrayList params = new ArrayList();
        String sql = "select * from attachment_folder where 1=1 ";
        if(StringUtils.isNotEmpty(folder)){
            sql += " and text like ?";
            params.add(processLike(folder));
        }
        List<AttachmentFolder> items = sql(sql).list(AttachmentFolder.class,params.toArray());
        return items;
    }

    public String saveAttachment(MultipartFile file) throws Exception{

        String relativeFolder = Constants.ATTACHMENT_UPLOAD_PATH+"/";

        String nowTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        String fileName = nowTime+"_"+ UUID.randomUUID()+ ImageUtil.getFileExt(file);
        //如果上传目录为/static/images/upload/，则可以如下获取：
        File absFolder = new File(Constants.webRoot.getAbsolutePath(),relativeFolder);
        if(!absFolder.exists()) absFolder.mkdirs();
        System.out.println("upload url:"+absFolder.getAbsolutePath());
        //在开发测试模式时，得到的地址为：{项目跟目录}/target/static/images/upload/
        //在打包成jar正式发布时，得到的地址为：{发布jar包目录}/static/images/upload/
        File oriFile = new File(absFolder,fileName);
        file.transferTo(oriFile);
        return relativeFolder+fileName;
    }

    public List<Attachment> getByIds(String ids){
        String[] idArray = ids.split(",");
        List<Attachment> attachments = sql("select * from attachment where id in ("+genePlaceHolders(idArray.length)+")").list(Attachment.class,idArray);
        return attachments;
    }

    public File getFile(Attachment attachment){
       return new File(Constants.webRoot.getAbsolutePath(),attachment.getPath());
    }

    public void del(String ids) throws Exception{
        List<Attachment> items = getByIds(ids);
        for(Attachment item:items){
            File file = getFile(item);
            if(file.exists()){
                file.delete();
            }
        }
        deleteByIds(Attachment.class,ids);
    }



}
